package com.zhaotianhao.util;

import com.zhaotianhao.pojo.Files;
import com.zhaotianhao.service.FilesService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @Author Z-7
 * @Date 2022/3/2
 */
@Lazy(false)
@Component
@EnableScheduling
public class TaskClean {
    // 上传的根路径
    @Value("d:/imgs")
    private String uploadPath;

    // 路径的分隔符号
    private String pathSpit="/";
    @DubboReference
    private FilesService filesService;

    /**
     * 每分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void clear() {
        List<Files> files = filesService.selectUnused();
        System.out.println("定时执行。。。" + new Date());
        // 获取5分钟之前的文件
        for (Files file : files) {
            File delFile = new File(uploadPath + pathSpit + file.getPath());
            if(delFile.exists()){
                delFile.delete();
                filesService.deleteById(file.getId());
            }
        }
    }
}
